Recursion and Dynamic Programming: Uplevel Your Coding Interview by Wong Jack

Recursion and Dynamic Programming: Uplevel Your Coding Interview by Wong Jack

Author:Wong, Jack [Wong, Jack]
Language: eng
Format: epub
Published: 2018-08-23T16:00:00+00:00


Approach 2: top-down dynamic programming (memoization)

Notice that there are some overlapping subproblems the above code repeatedly solves. We can improve the program run time by caching (saving) the result for quick reference, and therefore avoid the recomputation of the subproblem again. Here is the caching approach:

/**

@param {number} n - balance

@param {number []} denoms - coin denominators. [25, 10, 5, 1] in this case

@param {number} index - current denominator index (start with 0)

@param {Object} memo - the cache object for computed subproblems, where it is initialized to {}

*/

function findChange (n, denoms, index, memo) {

var memoKey = n + ':' + denoms[index],

denom = denoms[index],

ways = 0,

remainingAmount = 0;

if (memo[memoKey]) return memo[memoKey];

if (index >= (denoms.length - 1)) return 1;

for (var i = 0; (i * denom) <= n; i++) {

remainingAmount = n - (i * denom);

ways += findChange(remainingAmount, denoms, index + 1, memo);

}

memo[memoKey] = ways;

return ways;

}



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.